#include "AnimatedSprite.h"

#include "ResourceDatabase.h"
#include "ResImage.h"

AnimatedSprite::AnimatedSprite()
// : columns(0)
// , rows(0)
// , frameWidth(0)
// , frameHeight(0)
: animIndexPlayed(0)
, frame(0)
{
}

AnimatedSprite::AnimatedSprite(int imageId)
//     : columns(columns)
//     , rows(rows)
: animIndexPlayed(0)
, frame(0)
, imageId(imageId)
{    
//     frameWidth = columns != 0 ? image.GetWidth() / columns : GetImage()->GetWidth();
//     frameHeight = rows != 0 ? image.GetHeight() / rows : GetImage()->GetHeight();
    rect = sf::Rect<int>(0, 0, ResourceDatabase::get().getImage(imageId)->getFrameWidth(), ResourceDatabase::get().getImage(imageId)->getFrameHeight());
    SetImage(*ResourceDatabase::get().getImage(imageId));
}

AnimatedSprite::~AnimatedSprite()
{
}



void AnimatedSprite::setSubRect( int index )
{
    int frameColumn = (int)index % ResourceDatabase::get().getImage(imageId)->getColumns();
    int frameRow = (int)index / ResourceDatabase::get().getImage(imageId)->getColumns();

    int dx = frameColumn * ResourceDatabase::get().getImage(imageId)->getFrameWidth() - rect.Left;
    int dy = frameRow * ResourceDatabase::get().getImage(imageId)->getFrameHeight() - rect.Top;

    rect.Left += dx;
    rect.Top += dy;
}



void AnimatedSprite::update(float delta)
{
    if (ResourceDatabase::get().getImage(imageId)->getColumns() > 1 || ResourceDatabase::get().getImage(imageId)->getRows() > 1)
    {
        frame += delta * animations[animIndexPlayed].getLength() / animations[animIndexPlayed].getTime();

        if((int)frame >= animations[animIndexPlayed].getLength())
        {
            frame = frame - int(frame);
        }
        setSubRect(frame + animations[animIndexPlayed].getRowBegin()*ResourceDatabase::get().getImage(imageId)->getColumns() + animations[animIndexPlayed].getColumnBegin());
        SetSubRect(rect);
    }
    SetImage(*ResourceDatabase::get().getImage(imageId));
}

bool AnimatedSprite::playAnimation( int animationId )
{
    bool animationExist = false;
    size_t i = 0;
    for (; i < animations.size(); i++)
    {
        if (animations[i].getAnimationId() == animationId)
        {
            animationExist = true;
            break;
        }
    }
    if (animationExist)
    {
        animIndexPlayed = i;
        frame = 0;
    }
    return false;
}

void AnimatedSprite::addAnimation( Animation animation )
{
    animations.push_back(animation);
}

int AnimatedSprite::getImageId() const
{
    return imageId;
}
